package com.durian.ui.dialog;

import android.content.Context;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;

import androidx.annotation.LayoutRes;
import androidx.annotation.Nullable;
import androidx.annotation.StyleRes;
import androidx.fragment.app.DialogFragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import androidx.viewbinding.ViewBinding;

import com.durian.base.R;


/**
 * 说明：BaseNiceDialog
 * <p/>
 * 作者：fanly
 * <p/>
 * 类型：Class
 * <p/>
 * 时间：2017/8/7 16:40
 * <p/>
 * 版本：version 1.0
 */

public abstract class BaseNiceDialog extends DialogFragment {

    private static final String   MARGIN = "margin";
    private static final String   WIDTH = "width";
    private static final String   HEIGHT = "height";
    private static final String   DIM = "dim_amount";
    private static final String   BOTTOM = "show_bottom";
    private static final String   CANCEL = "out_cancel";
    private static final String   ANIM = "anim_style";
    private static final String   LAYOUT = "layout_id";
    private              int      margin;//左右边距
    private              int      width;//宽度
    private              int      height;//高度
    private              float    dimAmount = 0.5f;//灰度深浅
    private              boolean  showBottom;//是否底部显示
    private              boolean  outCancel = true;//是否点击外部取消
    @StyleRes
    private              int      animStyle;
    @LayoutRes
    protected            int      layoutId;

    public View bindRootView(LayoutInflater inflater,ViewGroup viewGroup){
        return null;
    }

    public abstract int intLayoutId();

    public abstract void convertView(ViewHolder holder, BaseNiceDialog dialog);

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setStyle(DialogFragment.STYLE_NO_TITLE, R.style.base_ui_nice_dialog);
        layoutId = intLayoutId();

        //恢复保存的数据
        if (savedInstanceState != null) {
            margin = savedInstanceState.getInt(MARGIN);
            width = savedInstanceState.getInt(WIDTH);
            height = savedInstanceState.getInt(HEIGHT);
            dimAmount = savedInstanceState.getFloat(DIM);
            showBottom = savedInstanceState.getBoolean(BOTTOM);
            outCancel = savedInstanceState.getBoolean(CANCEL);
            animStyle = savedInstanceState.getInt(ANIM);
            layoutId = savedInstanceState.getInt(LAYOUT);
        }
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = bindRootView(inflater,container);
        if (view == null){
            view = inflater.inflate(layoutId, container, false);
        }
        convertView(ViewHolder.create(view), this);
        return view;
    }

    @Override
    public void onStart() {
        super.onStart();
        initParams();
    }

    /**
     * 屏幕旋转等导致DialogFragment销毁后重建时保存数据
     *
     * @param outState
     */
    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putInt(MARGIN, margin);
        outState.putInt(WIDTH, width);
        outState.putInt(HEIGHT, height);
        outState.putFloat(DIM, dimAmount);
        outState.putBoolean(BOTTOM, showBottom);
        outState.putBoolean(CANCEL, outCancel);
        outState.putInt(ANIM, animStyle);
        outState.putInt(LAYOUT, layoutId);
    }

    private void initParams() {
        Window window = getDialog().getWindow();
        if (window != null) {
            //设置dialog进入、退出的动画
            window.setWindowAnimations(animStyle);
            WindowManager.LayoutParams lp = window.getAttributes();
            //调节灰色背景透明度[0-1]，默认0.5f
            lp.dimAmount = dimAmount;
            //是否在底部显示
            if (showBottom) {
                lp.gravity = Gravity.BOTTOM;
            }
            //设置dialog宽度
            if (width == 0) {
                lp.width = screenWidth() - 2 * margin;
            } else {
                lp.width = width;
            }
            //设置dialog高度
            if (height == 0) {
                lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
            } else {
                lp.height = height;
            }

            window.setAttributes(lp);
        }
        setCancelable(outCancel);
    }

    public BaseNiceDialog setMargin(int margin) {
        this.margin = margin;
        return this;
    }


    public BaseNiceDialog setWidth(int width) {
        this.width = width;
        return this;
    }

    public BaseNiceDialog setHeight(int height) {
        this.height = height;
        return this;
    }

    public BaseNiceDialog setDimAmount(float dimAmount) {
        this.dimAmount = dimAmount;
        return this;
    }

    public BaseNiceDialog setShowBottom(boolean showBottom) {
        this.showBottom = showBottom;
        return this;
    }

    public BaseNiceDialog setOutCancel(boolean outCancel) {
        this.outCancel = outCancel;
        return this;
    }

    public BaseNiceDialog setAnimStyle(@StyleRes int animStyle) {
        this.animStyle = animStyle;
        return this;
    }

    public void dismiss(){
        if (isVisible()){
            super.dismiss();
        }
    }

    public String getBundleString(String key, String defValue){
        Bundle bundle = getArguments();
        if (TextUtils.isEmpty(key) || bundle == null || !bundle.containsKey(key)){
            return defValue;
        }else {
            return bundle.getString(key);
        }
    }

    private int screenWidth(){
        WindowManager wm = (WindowManager) getContext().getApplicationContext().getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics dm = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(dm);
        return dm.widthPixels;
    }

    private int screenHeight(){
        WindowManager wm = (WindowManager) getContext().getApplicationContext().getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics dm = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(dm);
        return dm.heightPixels;
    }

    public BaseNiceDialog show(FragmentManager manager) {
        FragmentTransaction transaction = manager.beginTransaction();
        transaction.add(this, String.valueOf(System.currentTimeMillis()));
        transaction.commitAllowingStateLoss();
        return this;
    }
}
